import {
  asyncSetInterval,
  fixZeroInfo,
  getSearchString,
  notifications
} from '../../lib/zeroReportUtils.js';
import { cwbbReport } from './cwbbReport.js';

const pages = {
  indexLogin:
    'https://etax.shenzhen.chinatax.gov.cn/bszm-web/apps/views/beforeLogin/indexBefore/pageIndex.html',
  pageIndex:
    'https://etax.shenzhen.chinatax.gov.cn/bszm-web/apps/views/companyPage/desktopTax.html',
  reprotIndex:
    'https://etax.shenzhen.chinatax.gov.cn/bszm-web/apps/views/publicPage/byysb/byysb.html',
  xgmSetp1:
    'https://etax.shenzhen.chinatax.gov.cn/BsfwtWeb/apps/views/sb/xgmsb/xgmzzs/sb_xgmsb_step1.html', // 小规模申报页面
  xgmSetp2:
    'https://etax.shenzhen.chinatax.gov.cn/BsfwtWeb/apps/views/sb/xgmsb/xgmzzs/sb_xgmsb_step2.html',
  xgmSetp3:
    'https://etax.shenzhen.chinatax.gov.cn/BsfwtWeb/apps/views/sb/xgmsb/xgmzzs/sb_xgmsb_step3.html',
  xgmSetp4:
    'https://etax.shenzhen.chinatax.gov.cn/BsfwtWeb/apps/views/sb/xgmsb/xgmzzs/sb_xgmsb_step4.html',
  xgmSetp5:
    'https://etax.shenzhen.chinatax.gov.cn/BsfwtWeb/apps/views/sb/xgmsb/xgmzzs/sb_xgmsb_step5.html',
  qsReprotIndex:
    'https://etax.shenzhen.chinatax.gov.cn/sbzx-web/apps/views/sb_sdsA_yj_new_202006/sb_sdsA_yj_new.html', // 企业所得税申报页面
  reprotSuccess1:
    'https://etax.shenzhen.chinatax.gov.cn/BsfwtWeb/pages/sb/sb_ts.html?xgmsb',
  reprotSuccess2:
    'https://etax.shenzhen.chinatax.gov.cn/sbzx-web/apps/views/public/sb_success.html?sbzlDm=10442&v=1593671063831_2.0.0',
  reprotResult:
    'https://etax.shenzhen.chinatax.gov.cn/BsfwtWeb/apps/views/sb/cxdy/sbcx.html',
  cwbbIndex:
    'https://etax.shenzhen.chinatax.gov.cn/sbzx-web/apps/views/sb_cwbb_xqy_kjzz/sb_cwbb_xqy_kjzz.html'
};

const closeYd = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let closeydBtn1 = $(
        '#layui-layer1 .layui-layer-btn > .layui-layer-btn0'
      )[0];
      if (closeydBtn1) {
        closeydBtn1.click();
      }
      setTimeout(() => {
        let closeydBtn2 = $(
          '#layui-layer2 .layui-layer-btn > .layui-layer-btn0'
        )[0];
        if (closeydBtn2) {
          closeydBtn2.click();
        }
        resolve(true);
      }, 500);
    }, 500);
  });
};

const pageIndex = async (currentZeroInfo) => {
  // 关闭引导
  await closeYd();
  let url = $(
    '#left-menu > div.menu-div.menu-tcyw > ul > li:nth-child(4) > a'
  ).attr('data-url');
  if (url) {
    window.location.href = url;
  }
};

const reprotIndex = async (currentZeroInfo) => {
  let lis = $('#byysbContent > li');
  if (currentZeroInfo.recordList.length === 0) {
    let recordList = Array.from(lis)
      .filter((item) => $(item).find('span:eq(0)').text() !== '申报种类')
      .map((item) => {
        let declareName = $(item).find('span:eq(0)').text();
        let date = $(item).find('span:eq(1)').text().split('~');
        let endPeriod = currentZeroInfo.endPeriod > 9 || ('0' + currentZeroInfo.endPeriod);
        let bsssqz = [currentZeroInfo.year, endPeriod];
        let month = 1;

        if (declareName.includes('季报')) month = 2;
        if (date.length > 1) {
          bsssqz = date[1].split('-');
          month = Number(date[1].split('-')[1]) - Number(date[0].split('-')[1]);
        }

        let isSuccess = $(item).find('span:eq(3)').text().includes('申报成功');
        return {
          declareName,
          accountBook: `${bsssqz[0]}-${bsssqz[1]}`,
          declareCycle:
            month === 11 ? 'year' : month === 2 ? 'season' : 'month',
          isSuccess
        };
      });
    fixZeroInfo({ recordList });
    setTimeout(() => {
      window.location.reload();
    }, 1000);
  } else {
    // 财务报表
    let cwbb = currentZeroInfo.recordList.find((item) => item.declareName.includes('财务报表'));
    let cwbbli = Array.from(lis).find((item) => $(item).find('span:eq(0)').text().includes(cwbb.declareName));
    if (cwbb && !cwbb.isSuccess && currentZeroInfo.customerType.includes('小企业会计准则') && cwbbli) {
      $(cwbbli).find('.operate > .ckjdBtn')[0].click();
      return;
    }
    // 小规模增值税
    let xgmData = currentZeroInfo.recordList.find((item) => item.declareName === '小规模增值税季报');
    let xgm = Array.from(lis).find((item) => $(item).find('span:eq(0)').text().includes('小规模增值税季报'));
    if (xgmData && !xgmData.isSuccess && xgm) {
      $(xgm).find('.operate > .ckjdBtn')[0].click();
      return;
    }
    // 企业所得税
    let qsData = currentZeroInfo.recordList.find((item) => item.declareName === '企业所得税A类季报');
    let qs = Array.from(lis).find((item) => $(item).find('span:eq(0)').text().includes('企业所得税A类季报'));
    if (qsData && !qsData.isSuccess && qs) {
      $(qs).find('.operate > .ckjdBtn')[0].click();
      return;
    }
    window.location.href = pages.reprotResult;
  }
};

const xgmSetp1 = async (currentZeroInfo) => {
  asyncSetInterval(() => {
    let iframe = $('.mini-panel-border .mini-panel-body iframe');
    let loading = $(
      '#cekcWindow > div > div.mini-panel-viewport > div.mini-panel-body > div > div.mini-mask-msg.mini-mask-loading'
    );
    if (iframe.length && loading.length === 0) {
      iframe.contents().find('a.mini-button:eq(1)')[0].click();
      return true;
    }
  }, 1000).then(() => {
    $('#nextStep')[0].click();
    asyncSetInterval(() => {
      let iframe1 = $('.mini-panel-border .mini-panel-body > iframe');
      if (iframe1.length) {
        return iframe1;
      }
    }, 500).then((iframe) => {
      iframe.contents().find('.btn > a')[0].click();
    });
  });
};

const xgmSetp5 = async (currentZeroInfo) => {
  const tabTd = $('.mini-tabs-table .mini-tabs-headers table tr td');
  const tab1 = tabTd[1];
  const tab2 = tabTd[3];
  const tab3 = tabTd[5];
  const tab4 = tabTd[7];
  tab2.click();
  asyncSetInterval(() => {
    tab3.click();
    return asyncSetInterval(() => {
      tab4.click();
      return true;
    });
  })
    .then(() => {
      return asyncSetInterval(() => {
        $('#pbbd').click();
        return true;
      });
    })
    .then(() => {
      return asyncSetInterval(() => {
        let msgBox = $('.mini-messagebox');
        if (msgBox.length) {
          msgBox.find('.mini-button').click();
          return true;
        }
      }, 3000);
    })
    .then(() => {
      return asyncSetInterval(() => {
        $('#nextStep').click();
        return true;
      });
    })
    .then(() => {
      return asyncSetInterval(() => {
        let iframe = $('.mini-panel-border .mini-panel-body iframe');
        if (iframe.length) {
          return iframe.contents();
        }
      }, 3000);
    })
    .then((iframe) => {
      asyncSetInterval(() => {
        iframe.find('.show-tab > .mt30 > a')[0].click();
        return true;
      }, 3000);
    });
};

const qsReprotIndex = async (currentZeroInfo) => {
  console.log(currentZeroInfo);
  const tabTd = $('.mini-tabs-table .mini-tabs-headers table tr td');
  const tab1 = tabTd[1];
  const tab2 = tabTd[3];
  const tab3 = tabTd[5];
  const tab4 = tabTd[7];
  const tab5 = tabTd[9];
  const tab6 = tabTd[11];
  asyncSetInterval(() => {
    let msgBox = $('.mini-messagebox');
    let tips = '系统检测到您上次填写了申报表';
    if (msgBox.find('.mini-messagebox-content').text().includes(tips)) {
      msgBox.find('.mini-button:eq(1)')[0].click();
    }
    return true;
  })
    .then(() => {
      return asyncSetInterval(() => {
        let msgBox = $('.mini-messagebox');
        if (msgBox.length) {
          msgBox.find('.mini-button:eq(0)')[0].click();
        }
        return true;
      });
    })
    .then(() => {
      return asyncSetInterval(() => {
        let msgBox = $('.mini-messagebox');
        if (msgBox.length) {
          msgBox.find('.mini-button:eq(0)')[0].click();
        }
        return true;
      })
        .then(() => {
          return asyncSetInterval(() => {
            tab2.click();
            return true;
          });
        })
        .then(() => {
          return asyncSetInterval(() => {
            tab3.click();
            return true;
          });
        })
        .then(() => {
          return asyncSetInterval(() => {
            tab4.click();
            return true;
          });
        })
        .then(() => {
          return asyncSetInterval(() => {
            tab5.click();
            return true;
          });
        })
        .then(() => {
          return asyncSetInterval(() => {
            tab6.click();
            return true;
          });
        })
        .then(() => {
          return asyncSetInterval(() => {
            tab1.click();
            return true;
          });
        })
        .then(() => {
          return asyncSetInterval(() => {
            $('#gjxzhjzhy .mini-list-inner .mini-checkboxlist-item:eq(1)')
              .find('input')[0]
              .click();
            $('#kjxqy .mini-list-inner .mini-checkboxlist-item:eq(1)')
              .find('input')[0]
              .click();
            $('#jsdy .mini-list-inner .mini-checkboxlist-item:eq(1)')
              .find('input')[0]
              .click();
            // 从业人数
            let cyrsList = $('.mini-tabs-bodys > .mini-tabs-body:nth-child(1) .sb_table > tbody > tr:nth-child(6) > td.enable')
            Array.from(cyrsList).forEach(item => {
              let ipt =  $(item).find('input');
              if (ipt.val() == 0) {
                ipt.val(1)
              }
            })
            // 资产总额
            let zczeList = $('.mini-tabs-bodys > .mini-tabs-body:nth-child(1) .sb_table > tbody > tr:nth-child(7) > td.enable');
            zczeList = Array.from(zczeList).slice(0,-2);
            zczeList.forEach(item => {
              let num = $(item).find('input');
              if (num.val() == 0) {
                num.val(0.01);
              }
            })
            let endSeason = $(
              '.mini-tabs-bodys > .mini-tabs-body:nth-child(1) .sb_table > tbody > tr:nth-child(7) > td.enable:eq(-1) > input'
            );
            let startSeason = $(
              '.mini-tabs-bodys > .mini-tabs-body:nth-child(1) .sb_table > tbody > tr:nth-child(7) > td.enable:eq(-2) > input'
            );
            startSeason.val(
              parseFloat(currentZeroInfo.quarterSum / 10000) || 0.01
            );
            endSeason.val(parseFloat(currentZeroInfo.endSum / 10000) || 0.01);
            return true;
          });
        })
        .then(() => {
          return asyncSetInterval(() => {
            $('#sb_save').click();
            return true;
          });
        })
        .then(() => {
          return asyncSetInterval(() => {
            let msgBox = $('.mini-messagebox');
            if (msgBox.length) {
              msgBox.find('.mini-button:eq(0)')[0].click();
            }
            return true;
          });
        });
    });
};

const reprotResult = async (currentZeroInfo) => {
  let zeroReportEnd = getSearchString('zeroReportEnd');
  if (!zeroReportEnd) {
    asyncSetInterval(() => {
      let $els = $('#mini-grid-table-bodysbqkGrid > tbody > .mini-grid-row');
      let xgm = Array.from($els).find((item) => $(item).text().includes('《增值税纳税申报表（小规模纳税人适用）》'));
      let qs = Array.from($els).find((item) => $(item).text().includes('《A200000中华人民共和国企业所得税月（季）度预缴纳税申报表（A类，2018年版）》'));
      let cwbb = Array.from($els).find(item => $(item).text().includes('企业财务报表'));

      let newRecordList = [...currentZeroInfo.recordList];
      let isReprotXgm;
      let isReprotQs;
      if (xgm) {
        isReprotXgm = $(xgm).find('td:eq(5)').text() === '申报成功';
        let idx = currentZeroInfo.recordList.findIndex(
          (item) => item.declareName === '小规模增值税季报'
        );
        if (idx > -1) {
          newRecordList[idx].isSuccess = isReprotXgm;
        }
      }
      if (qs) {
        isReprotQs = $(qs).find('td:eq(5)').text() === '申报成功';
        let idx = currentZeroInfo.recordList.findIndex(
          (item) => item.declareName === '企业所得税A类季报'
        );
        if (idx > -1) {
          newRecordList[idx].isSuccess = isReprotQs;
        }
      }
      if (cwbb) {
        let idx = currentZeroInfo.recordList.findIndex(
          (item) => item.declareName.includes('财务报表报送与信息采集')
        );
        if (idx > -1) {
          newRecordList[idx].isSuccess = $(cwbb).find('td:eq(5)').text() === '申报成功';
        }
      }
      fixZeroInfo({ recordList: newRecordList }); // 如果小规模和企税有申报成功则同步信息
      return true;
    }, 1000).then(() => {
      return asyncSetInterval(() => {
        let xgm = currentZeroInfo.recordList.find(
          (item) => item.declareName === '小规模增值税季报'
        );
        let qs = currentZeroInfo.recordList.find(
          (item) => item.declareName === '企业所得税A类季报'
        );
        let cwbb = currentZeroInfo.recordList.find(
          (item) => item.declareName.includes('财务报表报送与信息采集')
        );
        let isXqykjzz = currentZeroInfo.customerType.includes('小企业会计准则');
        if (((xgm && xgm.isSuccess) || !xgm) && ((qs && qs.isSuccess) || !qs) && ((cwbb && (!isXqykjzz || cwbb.isSuccess)) || !cwbb)) {
          if (!isXqykjzz) {
            notifications({ message: '财务报表制度不一样，请保持税局和系统的制度相同' });
          }
          window.postMessage(
            {
              event: 'zeroReportBack',
              data: { ...currentZeroInfo }
            },
            '*'
          );
        } else {
          window.location.href = pages.reprotIndex; // 小规模和企税没有申报完成跳该页面继续走申报流程
          return true;
        }
        return true;
      });
    });
  }
};

export function zeroReprot(currentZeroInfo) {
  let href = window.location.href;
  if (href.includes(pages.pageIndex)) {
    // 首页相关
    pageIndex(currentZeroInfo);
  }
  if (href.includes(pages.reprotIndex)) {
    reprotIndex(currentZeroInfo); // 本月应申报税种页面
  }
  // 财务报表
  if (href.includes(pages.cwbbIndex)) {
    cwbbReport(currentZeroInfo);
  }
  if (href.includes(pages.xgmSetp1)) {
    // 小规模申报流程-步骤1
    xgmSetp1(currentZeroInfo);
  }
  if (href.includes(pages.xgmSetp2)) {
    // 小规模申报流程-步骤2
    $('#nextStep')[0].click();
  }
  if (href.includes(pages.xgmSetp3)) {
    // 小规模申报流程-步骤3
    $('#nextStep')[0].click();
  }
  if (href.includes(pages.xgmSetp4)) {
    // 小规模申报流程-步骤4
    $('#nextStep')[0].click();
  }
  if (href.includes(pages.xgmSetp5)) {
    // 小规模申报流程-步骤5
    xgmSetp5(currentZeroInfo);
  }
  if (href.includes(pages.qsReprotIndex)) { // 企业所得税申报流程
    qsReprotIndex(currentZeroInfo);
  }
  if (href.includes(pages.reprotResult)) { // 申报结果页
    reprotResult(currentZeroInfo);
  }
}
